package com.zp.mall.product.service.impl;

import com.zp.mall.product.dao.BrandDao;
import com.zp.mall.product.dao.CategoryDao;
import com.zp.mall.product.entity.BrandEntity;
import com.zp.mall.product.entity.CategoryEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zp.common.utils.PageUtils;
import com.zp.common.utils.Query;

import com.zp.mall.product.dao.CategoryBrandRelationDao;
import com.zp.mall.product.entity.CategoryBrandRelationEntity;
import com.zp.mall.product.service.CategoryBrandRelationService;
import org.springframework.transaction.annotation.Transactional;


@Service("categoryBrandRelationService")
public class CategoryBrandRelationServiceImpl extends ServiceImpl<CategoryBrandRelationDao, CategoryBrandRelationEntity> implements CategoryBrandRelationService {
    @Autowired
    private CategoryDao categoryDao;
    @Autowired
    private BrandDao brandDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryBrandRelationEntity> page = this.page(
                new Query<CategoryBrandRelationEntity>().getPage(params),
                new QueryWrapper<CategoryBrandRelationEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveCategoryBrandRelationEntity(CategoryBrandRelationEntity categoryBrandRelation) {
        //查询出分类名称 和 品牌名称  也存入中间表中   在电商系统中 大表数据不做关联  提高数据库性能
        CategoryEntity categoryEntity = categoryDao.selectById (categoryBrandRelation.getCatelogId ());
        BrandEntity brandEntity = brandDao.selectById (categoryBrandRelation.getBrandId ());
        categoryBrandRelation.setCatelogName (categoryEntity.getName ());
        categoryBrandRelation.setBrandName (brandEntity.getName ());
        this.save (categoryBrandRelation); //保存
    }

    /**
     * 根据分类ID获取该分类下的所有品牌
     * @param catId
     * @return
     */
    @Override
    public List<BrandEntity> getRelationBrandsByCatId(Long catId) {
        //根据类别ID 获取 类别-品牌表的数据
        List<CategoryBrandRelationEntity> categoryBrandRelationEntities = this.list (new QueryWrapper<CategoryBrandRelationEntity> ().eq ("catelog_id", catId));

        //获取品牌根据 类别-品牌表的数据中的品牌ID
        List<BrandEntity> brandEntities = categoryBrandRelationEntities.stream ().map (c -> {
            return brandDao.selectById (c.getBrandId ());
        }).collect (Collectors.toList ());

        return brandEntities;
    }

}